package com.medicinezp.webapi;

import com.medicinezp.baseconfig.domain.*;
import com.medicinezp.baseconfig.service.*;
import com.medicinezp.common.config.AliConfig;
import com.medicinezp.common.config.MedicinezpConfig;
import com.medicinezp.common.core.controller.BaseController;
import com.medicinezp.common.core.domain.AjaxResult;
import com.medicinezp.common.core.domain.entity.SysUser;
import com.medicinezp.common.core.domain.model.LoginUser;
import com.medicinezp.common.core.page.TableDataInfo;
import com.medicinezp.common.utils.DateUtils;
import com.medicinezp.common.utils.SecurityUtils;
import com.medicinezp.common.utils.StringUtils;
import com.medicinezp.common.utils.file.FileUploadUtils;
import com.medicinezp.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 不需要授权接口
 *
 * @author waoqi
 * @date 2021-08-18
 */
@RestController
@RequestMapping("/api/profile")
public class ProfileController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private IBaseFeedbackService feedbackService;

    @Autowired
    private IBaseUserResumeService baseResumeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBaseUserIntentionService baseUserIntentionService;

    @Autowired
    private IBaseUserResumeEducationService baseResumeEducationService;

    @Autowired
    private IBaseUserResumeCertificateService baseResumeCertificateService;
    @Autowired
    private IBaseUserResumeExperienceService baseResumeExperienceService;

    @Autowired
    private IBaseUserResumeProjectService baseResumeProjectService;

    @Autowired
    private IBaseJobsService jobsService;

    @Autowired
    private IBaseCompanyService companyService;

    @Autowired
    private IBaseJobTypeService baseJobTypeService;

    @Autowired
    private IBaseUserJobApplyService baseUserJobApplyService;

    @Autowired
    private IBaseUserBrowserService baseUserBrowserService;

    @Autowired
    private IBaseUserCollectService baseUserCollectService;

    @Autowired
    private IBaseUserInviteApplyService baseUserInviteApplyService;


    @ApiOperation("查询当前用户信息")
    @GetMapping("/getUserDetal")
    public AjaxResult getUserDetal() {
        AjaxResult result = AjaxResult.success();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = sysUserService.selectUserById(loginUser.getUserId());
        if(currentUser!=null){
            currentUser.setDept(null);
        }
        result.put("userInfo", currentUser);
        BaseUserResume param=new BaseUserResume();
        param.setUserId(currentUser.getUserId());
        param.setType(1);
        List<BaseUserResume>  resumeList=baseResumeService.selectBaseUserResumeList(param);
        result.put("onlineResumeFlag",false);
        if(resumeList.size()>0){
            BaseUserResume userResume=resumeList.get(0);
            BaseUserResumeEducation eduParam=new BaseUserResumeEducation();
            eduParam.setResumeId(userResume.getId());
            List<BaseUserResumeEducation> eduList=baseResumeEducationService.selectBaseUserResumeEducationList(eduParam);

            BaseUserResumeExperience workParam=new BaseUserResumeExperience();
            workParam.setResumeId(userResume.getId());
            List<BaseUserResumeExperience> workExperienceList= baseResumeExperienceService.selectBaseUserResumeExperienceList(workParam);
            if(StringUtils.isNotEmpty(userResume.getAdvantage()) && eduList.size()>0){
                result.put("onlineResumeFlag",true);
            }
        }
        BaseUserResume defaultParam=new BaseUserResume();
        defaultParam.setUserId(currentUser.getUserId());
        defaultParam.setDefaultFlag("Y");
        List<BaseUserResume>  userResumeList=baseResumeService.selectBaseUserResumeList(defaultParam);
        if(userResumeList.size()>0){
            result.put("defaultResumeId",userResumeList.get(0).getId());
        }else{
            result.put("defaultResumeId",null);
        }

        return result;
    }

    @PostMapping("/motifyUserInfo")
    public AjaxResult motifyUserInfo(@Validated  @RequestBody SysUser userInfo){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user=new SysUser();
        user.setUserId(loginUser.getUser().getUserId());
        user.setAvatar(userInfo.getAvatar());
        user.setUserName(userInfo.getUserName());
        user.setBirthDate(userInfo.getBirthDate());
        user.setPhonenumber(userInfo.getPhonenumber());
        user.setSex(userInfo.getSex());
        return AjaxResult.success(sysUserService.updateUserStatus(user));

    }

    @GetMapping("/motifyUserPhone")
    public AjaxResult motifyUserPhone(@RequestParam(required = true, name = "phone") String phone){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user=new SysUser();
        user.setUserId(loginUser.getUser().getUserId());
        user.setPhonenumber(phone);
        return AjaxResult.success(sysUserService.updateUserStatus(user));

    }

    /**
     * 用户添加反馈信息
     * @param feedback
     * @return
     */
    @PostMapping("/feedBack/add")
    public AjaxResult addInfo(@Validated  @RequestBody BaseFeedback feedback){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        feedback.setUserId(loginUser.getUserId());
        feedback.setPhone(loginUser.getUser().getPhonenumber());
        feedback.setCreateTime(DateUtils.getNowDate());
        feedback.setCreateBy(loginUser.getUser().getPhonenumber());
        feedback.setStatus("01");
        return AjaxResult.success(feedbackService.insertBaseFeedback(feedback));

    }

    @ApiOperation("查询用户简在线历")
    @GetMapping("/getUserResumeDetal")
    public AjaxResult getUserResumeDetal() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BaseUserResume resume= baseResumeService.getUserResume(loginUser.getUserId());
        return AjaxResult.success(resume);
    }

    @ApiOperation("投递简历")
    @PostMapping("/userApplyJob")
    public AjaxResult userApplyJob(@RequestBody BaseUserJobApply baseUserJobApply)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BaseJobs job=jobsService.selectBaseJobsById(baseUserJobApply.getJobId());
        if(!"02".equals(job.getStatus())){
            return AjaxResult.error("岗位招聘已结束");
        }

        BaseUserResume  resume= baseResumeService.selectBaseUserResumeById(baseUserJobApply.getResumeId());
        if(resume==null){
            return AjaxResult.error("你还没有简历，快去填写简历吧");
        }
        BaseUserJobApply userParam=new BaseUserJobApply();
        userParam.setUserId(loginUser.getUserId());
        userParam.setJobId(baseUserJobApply.getJobId());
        List<BaseUserJobApply> applyList=baseUserJobApplyService.selectBaseUserJobApplyList(userParam);
        if(applyList.size()>0){
            return AjaxResult.error("你已经申请过该岗位了");
        }
        baseUserJobApply.setUserId(loginUser.getUserId());
        baseUserJobApply.setResumeId(baseUserJobApply.getResumeId());
        baseUserJobApply.setApplyTime(DateUtils.getNowDate());
        baseUserJobApply.setApplyStatus("01");
        int result=baseUserJobApplyService.insertBaseUserJobApply(baseUserJobApply);
        return toAjax(result);
    }

    @ApiOperation("我的投递")
    @GetMapping("/myJobApplyList")
    public TableDataInfo myJobApplyList(@RequestParam(required = false, name = "type") String type) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BaseJobs param=new BaseJobs();
        param.setId(loginUser.getUserId());
        param.setStatus(type);
        startPage();
        List<BaseJobs> list=jobsService.selectMyApplyJobsList(param);
        return getDataTable(list);
    }

    @ApiOperation("用户浏览职位")
    @GetMapping("/userBrowserJobs")
    public AjaxResult userBrowserJobs(@RequestParam(required = true, name = "id") Long id) {
        BaseUserBrowser param=new BaseUserBrowser();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        param.setUserId(loginUser.getUserId());
        param.setJobId(id);
        List<BaseUserBrowser> list= baseUserBrowserService.selectBaseUserBrowserList(param);
        if(list.size()>0){
            BaseUserBrowser info=list.get(0);
            info.setCreateTime(DateUtils.getNowDate());
            baseUserBrowserService.updateBaseUserBrowser(info);
            return AjaxResult.success("已经浏览过了");
        }else{

            param.setCreateTime(DateUtils.getNowDate());
            int result= baseUserBrowserService.insertBaseUserBrowser(param);
            return toAjax(result);
        }
    }

    @ApiOperation("用户浏览职位列表")
    @GetMapping("/userBrowserJobsList")
    public TableDataInfo userBrowserJobsList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BaseJobs param=new BaseJobs();
        param.setId(loginUser.getUserId());
        startPage();
        List<BaseJobs> jobList=  jobsService.selectUserBrowserJobsList(param);
        return getDataTable(jobList);
    }

    @ApiOperation("用户收藏职位/公司/职业")
    @GetMapping("/userCollectCompanyJobs")
    public AjaxResult userCollectCompanyJobs(@RequestParam(required = true, name = "id") Long id,
                                             @RequestParam(required = true, name = "type") String type) {
        BaseUserCollect param=new BaseUserCollect();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        param.setUserId(loginUser.getUserId());
        param.setType(type);
        param.setCollectId(id);
        List<BaseUserCollect> collectList= baseUserCollectService.selectBaseUserCollectList(param);
        if(collectList.size()>0){
            collectList.stream().forEach(collect->{
                baseUserCollectService.deleteBaseUserCollectById(collect.getId());
            });
            return AjaxResult.success("取消收藏成功");
        }else{
            param.setCreateTime(DateUtils.getNowDate());
            int result= baseUserCollectService.insertBaseUserCollect(param);
            return toAjax(result);
        }
    }

    @ApiOperation("用户收藏职位列表")
    @GetMapping("/userCollectDataList")
    public TableDataInfo userCollectDataList(@RequestParam(required = true, name = "type") String type) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if("01".equals(type)){
            BaseJobs param=new BaseJobs();
            param.setId(loginUser.getUserId());
            startPage();
            List<BaseJobs> jobList= jobsService.selectUserCollectJobsList(param);
            return getDataTable(jobList);
        }
        if("02".equals(type)){
            BaseCompany company=new BaseCompany();
            company.setId(loginUser.getUserId());
            startPage();
            List<BaseCompany> companyList=companyService.selectCollectCompanyList(company);
            return getDataTable(companyList);
        }
        if("03".equals(type)){
            BaseJobType jobType=new BaseJobType();
            jobType.setId(loginUser.getUserId());
            startPage();
            List<BaseJobType> secondType=baseJobTypeService.selectCollectJobTypeList(jobType);
            return getDataTable(secondType);
        }
        else{
            return getDataTable(new ArrayList<>());
        }

    }


    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = MedicinezpConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = AliConfig.getImgPrefix()+ fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("name",file.getOriginalFilename());
            ajax.put("fileName",file.getOriginalFilename());
            ajax.put("fileSize",file.getSize());
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("我的投递消息")
    @GetMapping("/myJobApplyMessage")
    public TableDataInfo myJobApplyMessage(@RequestParam(required = false, name = "type") String type,
                                           @RequestParam(required = false, name = "status") String status) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if("00".equals(type)){
            BaseJobs param=new BaseJobs();
            param.setId(loginUser.getUserId());
            startPage();
            List<BaseJobs> list=jobsService.selectMyAllJobsList(param);
            return getDataTable(list);
        }
        else if("01".equals(type)){
            BaseJobs param=new BaseJobs();
            param.setId(loginUser.getUserId());
            param.setStatus(status);
            startPage();
            List<BaseJobs> list=jobsService.selectMyApplyJobsList(param);
            return getDataTable(list);
        }
        else if("02".equals(type)){
            BaseJobs param=new BaseJobs();
            param.setId(loginUser.getUserId());
            startPage();
            List<BaseJobs> list=jobsService.selectMyInviteJobsList(param);
            return getDataTable(list);
        }
        else{
            return getDataTable(new ArrayList<>());
        }

    }


}
